// 性能监控工具
export class PerformanceMonitor {
  private static measurements: { [key: string]: number } = {};
  private static observers: PerformanceObserver[] = [];

  static startMeasurement(name: string) {
    this.measurements[name] = performance.now();
  }

  static endMeasurement(name: string): number {
    const startTime = this.measurements[name];
    if (!startTime) return 0;
    
    const duration = performance.now() - startTime;
    delete this.measurements[name];
    return duration;
  }

  static measureFunction<T extends (...args: any[]) => any>(
    fn: T,
    name: string
  ): T {
    return ((...args: any[]) => {
      this.startMeasurement(name);
      const result = fn(...args);
      
      if (result instanceof Promise) {
        return result.finally(() => {
          const duration = this.endMeasurement(name);
          console.log(`⚡ ${name}: ${duration.toFixed(2)}ms`);
        });
      } else {
        const duration = this.endMeasurement(name);
        console.log(`⚡ ${name}: ${duration.toFixed(2)}ms`);
        return result;
      }
    }) as T;
  }

  static observeLongTasks() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          if (entry.duration > 50) {
            console.warn(`🐌 Long Task detected: ${entry.duration.toFixed(2)}ms`);
          }
        }
      });

      observer.observe({ entryTypes: ['longtask'] });
      this.observers.push(observer);
    }
  }

  static observeLayoutShifts() {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          if ((entry as any).value > 0.1) {
            console.warn(`📏 Layout Shift detected: ${(entry as any).value.toFixed(4)}`);
          }
        }
      });

      observer.observe({ entryTypes: ['layout-shift'] });
      this.observers.push(observer);
    }
  }

  static getMemoryInfo() {
    const memory = (performance as any).memory;
    if (memory) {
      return {
        used: memory.usedJSHeapSize / 1024 / 1024,
        total: memory.totalJSHeapSize / 1024 / 1024,
        limit: memory.jsHeapSizeLimit / 1024 / 1024
      };
    }
    return null;
  }

  static logMemoryUsage() {
    const memInfo = this.getMemoryInfo();
    if (memInfo) {
      console.log(`🧠 Memory: ${memInfo.used.toFixed(1)}MB / ${memInfo.total.toFixed(1)}MB (${memInfo.limit.toFixed(1)}MB limit)`);
    }
  }

  static init() {
    this.observeLongTasks();
    this.observeLayoutShifts();
    
    // 定期记录内存使用情况
    setInterval(() => {
      this.logMemoryUsage();
    }, 30000); // 每30秒
  }

  static cleanup() {
    this.observers.forEach(observer => observer.disconnect());
    this.observers = [];
  }
}